package com.ouman.luoliluoli;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ouman.luoliluoli.models.LuoliTalkModel;
import com.ouman.luoliluoli.utils.GlobalConstants;
import com.ouman.luoliluoli.utils.NetworkHelper;
import com.ouman.luoliluoli.utils.TimeDisplayHelper;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import static android.widget.Toast.LENGTH_SHORT;

public class LuoliDetailActivity extends AppCompatActivity {

    private Integer talkId;
    private LuoliTalkModel luoliTalkModel;


    private ImageView imageViewAuthorAvatar;
    private TextView textViewTitle;
    private TextView textViewAuthorName;
    private TextView textViewAuthorSign;
    private TextView textViewTime;
    private TextView textViewContent;
    private ImageView imageViewNewsHeadImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_luoli_detail);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        luoliTalkModel = new LuoliTalkModel();

        imageViewAuthorAvatar = (ImageView) findViewById(R.id.imageViewAuthorAvatar);
        textViewTitle = (TextView) findViewById(R.id.textViewTitle);
        textViewAuthorName = (TextView) findViewById(R.id.textViewAuthorName);
        textViewAuthorSign = (TextView) findViewById(R.id.textViewAuthorSign);
        textViewTime = (TextView) findViewById(R.id.textViewTime);
        textViewContent = (TextView) findViewById(R.id.textViewContent);
        imageViewNewsHeadImage = (ImageView) findViewById(R.id.imageNewsHead);


        Bundle bundle = this.getIntent().getExtras();
        talkId = bundle.getInt("talkId");
        System.out.println(talkId);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_scrolling);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        if (NetworkHelper.isConnect(LuoliDetailActivity.this)){
            new Thread(getLuoliTalkThread).start();
        }else {
            Toast.makeText(this, "貌似没有网络连接啊", LENGTH_SHORT).show();
        }
    }

    //处理网络请求，获取新闻详情
    private  Thread getLuoliTalkThread = new Thread(){
        public void run(){

            HttpURLConnection connection = null;
            try {
                String urlAPI = GlobalConstants.API_LUOLI_TALK + "?news_id=" + talkId.toString();
                System.out.println("talk url: " + urlAPI);
                URL url = new URL(urlAPI);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                if (connection.getResponseCode() == 200){
                    InputStream is = connection.getInputStream();
                    String result = IOUtils.toString(is);
                    System.out.println(result);
                    is.close();

                    JSONObject jsonObject = new JSONObject(result);

                    String status = jsonObject.getString("status");
                    if (status.equals("success")){
                        JSONObject jsonItem = jsonObject.getJSONObject("data");
                        // 这里的news detail没有news id无需获取
                        int newsId = jsonItem.getInt("news_id");
                        String title = jsonItem.getString("news_title");
                        String authorName = jsonItem.getString("news_author_name");
                        String authorSign = jsonItem.getString("news_author_sign");
                        String authorAvatarUrl = jsonItem.getString("news_author_avatar_url");
                        String newsHeadImageUrl = jsonItem.getString("news_head_image_url");
                        String newsContent = jsonItem.getString("news_content");
                        String newsTime = jsonItem.getString("news_post_time");

                        Integer numWatched = jsonItem.getInt("news_num_watched");
                        Integer numLiked = jsonItem.getInt("news_num_liked");

                        luoliTalkModel.setNews_id(newsId);
                        luoliTalkModel.setNews_author_avatar_url(authorAvatarUrl);
                        luoliTalkModel.setNews_author_name(authorName);
                        luoliTalkModel.setNews_author_sign(authorSign);
                        luoliTalkModel.setNews_content(newsContent);
                        luoliTalkModel.setNews_head_image_url(newsHeadImageUrl);
                        luoliTalkModel.setNews_title(title);
                        luoliTalkModel.setNews_post_time(newsTime);

                        luoliTalkModel.setNews_num_watched(numWatched);
                        luoliTalkModel.setNews_num_liked(numLiked);

                        Message msg = Message.obtain();
                        msg.what = 0;
                        getDetailHandler.sendMessage(msg);

                    } else {
                        Message msg = Message.obtain();
                        msg.what = 1;
                        getDetailHandler.sendMessage(msg);
                    }

                }

            } catch (IOException e){
                e.printStackTrace();
            } catch (JSONException e){
                e.printStackTrace();
            } finally{
                if (connection != null){
                    connection.disconnect();
                }
            }

        }
    };

    private Handler getDetailHandler = new Handler(){
        public void handleMessage(Message msg){
            if (msg.what == 0){
                // 获取成功
                String postTime = TimeDisplayHelper.displayTime(luoliTalkModel.getNews_post_time());

                Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_talk);
                setSupportActionBar(toolbar);
                if (getSupportActionBar() != null){
                    getSupportActionBar().setTitle(luoliTalkModel.getNews_title());
                    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                }
                Glide.clear(imageViewAuthorAvatar);
                Glide.with(LuoliDetailActivity.this)
                        .load(luoliTalkModel.getNews_author_avatar_url())
                        .asBitmap()
                        .error(R.drawable.avatar1)
                        .into(imageViewAuthorAvatar);

                Glide.clear(imageViewNewsHeadImage);
                Glide.with(LuoliDetailActivity.this)
                        .load(GlobalConstants.API_BASE_URL + luoliTalkModel.getNews_head_image_url())
                        .asBitmap()
                        .error(R.drawable.real_random_2)
                        .into(imageViewNewsHeadImage);

                textViewTitle.setText(luoliTalkModel.getNews_title());
                textViewAuthorName.setText(luoliTalkModel.getNews_author_name());
                textViewAuthorSign.setText(luoliTalkModel.getNews_author_sign());
                textViewTime.setText(postTime);
                textViewContent.setText(luoliTalkModel.getNews_content());
            }else {
                Toast.makeText(LuoliDetailActivity.this, "获取详情失败", Toast.LENGTH_SHORT).show();
            }
        }
    };



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home){
            LuoliDetailActivity.this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
